package com.orchard.orchardfarmmanagementsystem.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.orchard.orchardfarmmanagementsystem.entity.Role;
import com.orchard.orchardfarmmanagementsystem.entity.User;
import com.orchard.orchardfarmmanagementsystem.entity.Permission;
import com.orchard.orchardfarmmanagementsystem.mapper.RoleMapper;
import com.orchard.orchardfarmmanagementsystem.mapper.UserMapper;
import com.orchard.orchardfarmmanagementsystem.mapper.PermissionMapper;
import com.orchard.orchardfarmmanagementsystem.pojo.CustomUserDetails;
import com.orchard.orchardfarmmanagementsystem.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
public class CustomUserDetailsService implements UserDetailsService {

    @Autowired
    private UserService userRepository;

    @Autowired
    private PermissionMapper permissionMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 查询用户信息
        User user = userRepository.findByUsername(username);

        // 加载用户的所有角色并添加 'ROLE_' 前缀
        List<Role> roles = roleMapper.selectRolesByUserId(user.getUserId());
        Set<String> roleNames = roles.stream()
                .map(role -> "ROLE_" + role.getName())
                .collect(Collectors.toSet());

        // 加载用户的所有权限
        List<Permission> permissions = permissionMapper.selectPermissionsByUserId(user.getUserId());
        Set<String> permissionCodes = permissions.stream()
                .map(Permission::getCode)
                .collect(Collectors.toSet());

        // 将角色和权限转换为 GrantedAuthority 列表
        Collection<? extends GrantedAuthority> authorities = Stream.concat(
                roleNames.stream().map(SimpleGrantedAuthority::new),
                permissionCodes.stream().map(SimpleGrantedAuthority::new)
        ).collect(Collectors.toList());

        return new org.springframework.security.core.userdetails.User(
                user.getUsername(),
                user.getPassword(),
                authorities
        );
    }
}